Vue.mixin({
    data: function () {
        return {
            serviceTypeInfo: { 0: '订阅号', 1: '升级后的订阅号', 2: '服务号' }
        };
    }
});

function clone(obj) {
    var copy;

    // Handle the 3 simple types, and null or undefined
    if (null == obj || "object" != typeof obj) return obj;

    // Handle Date
    if (obj instanceof Date) {
        copy = new Date();
        copy.setTime(obj.getTime());
        return copy;
    }

    // Handle Array
    if (obj instanceof Array) {
        copy = [];
        for (var i = 0, len = obj.length; i < len; i++) {
            copy[i] = clone(obj[i]);
        }
        return copy;
    }

    // Handle Object
    if (obj instanceof Object) {
        copy = {};
        for (var attr in obj) {
            if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);
        }
        return copy;
    }

    throw new Error("Unable to copy obj! Its type isn't supported.");
}

Array.prototype.unique = function(){
    var arr = this, o={}, newArr = [], i, n;
    for ( i = 0; i<arr.length; i++) {
        n = arr[i] + typeof(arr[i]);//如果不需要类型判断，直接将后面的去掉即可
        if (typeof(o[n]) === "undefined"){
            newArr[newArr.length] = arr[i]
            o[n] = 1;//缓存
        }
    }
    return newArr;
};

Array.prototype.indexOf = function(val) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == val) return i;
    }
    return -1;
};

Array.prototype.remove = function(val) {
    var index = this.indexOf(val);
    if (index > -1) {
        this.splice(index, 1);
    }
};

// 逻辑业务的错误处理
window.errorInfo = function (resData) {
    var status = resData.status
        , code = resData.code
        , error = resData.error
        , data = resData.data;
    return new Promise(function (resolve, reject) {
        if (status == 0) {
            resolve(resData);
        } else {
            reject(resData);
        }
    });
}

/**
    * 聚合数据
    * @param data 获取数据集，默认会将第一个数组为主
    * @param key 对应类型
    * 例如 [ { key: 'contact_id', key2: 'id', srcName: 'name', targetName: 'contact_name' }, ... ]
    * key 主数据集中判断相等条件key
    * key2 待集合数据集中判断相等条件key
    * srcName 待集合数据集中要获取的key
    * targetName 设定主数据集中需要增加的字段key
    * @param primaryIndex 设定哪一个数组是主要数组
*/
function myMixinData (data, key, primaryIndex) {
    for (let p in data) {
        if (!data[p]) return null;
    }
    let dataStr = []
        , _primaryIndex = primaryIndex ? primaryIndex : 0;
    for (var p in data) {
        dataStr.push(data[p]);
    }
    // 定义主对象与合并对象
    let primaryData = dataStr[_primaryIndex];
    dataStr.splice(_primaryIndex, 1);
    let otherData = dataStr;

    if (otherData.length != key.length) {
        throw new Error('合并对象数量与key的数量不一致');
    }

    // 开始合并
    let myMerge = primaryData.map(function (currentValue) {
        key.forEach(function (keyData, index) {
            otherData[index].forEach(function (data) {
                let keyValue = currentValue[keyData.key];
                let key2Value = data[keyData.key2];
                let srcName = keyData.srcName;
                let targetName = keyData.targetName;
                if (keyValue == key2Value) {
                    currentValue[targetName] = data[srcName];
                    return;
                }
            });
        });
        return currentValue;
    });
    return myMerge;
}


// 权限错误处理
var handleEx = function (resData) {
    var instance = this;
    if (resData.status == 401) { // 未登录
        sessionStorage.removeItem('token');
        sessionStorage.removeItem('token-expired');
//        sessionStorage.removeItem('a_li_baba');
//        sessionStorage.removeItem('depList');
//        sessionStorage.removeItem('depdList');
        window.location.href = Vue.http.options.root + "/ajax/login";
        return;
    } else if (resData.status == 403) { // 无权限
        return new Promise(function (resolve, reject) {
            reject({error: '错误：您没有访问当前功能的权限！'});
        });
    } else {
        return new Promise(function (resolve, reject) {
            reject(resData);
        });
    }
};

Vue.prototype.myGet = function (url, param) {
    var instance = this;
    // 判断session过期
    let time = Carevault.tokenExpiredRemainSeconds();
    if (time <= 2 && time >= 0) { // session剩余时间小于2分钟
        Carevault.refreshToken();
    }

    var func = null;
    if (param) {
        func = this.$http.get(this.$http.options.root + url, {
            params: param
        });
    } else {
        func = this.$http.get(this.$http.options.root + url);
    }
    return func.then(function (res) {
        return errorInfo(res.body);
    }, function (res) {
        return handleEx.call(instance, res.body);
    });
};

const config = [{key: 'post', label: 'myPost'}, {key: 'patch', label: 'myPatch'}, {key: 'delete', label: 'myDelete'}];

config.forEach(node => {
    Vue.prototype[node.label] = function (url, param) {
        var instance = this;
        return this.$http[node.key](this.$http.options.root + url, param)
        .then(function (res) {
            return errorInfo(res.body);
        }, function (res) {
            return handleEx.call(instance, res.body);
        });
    };
});

// 合并数组
(function () {
    function chunk (collection, size) {
        var result = [];

        // default size to two item
        size = parseInt(size) || 2;

        // add each chunk to the result
        for (var x = 0; x < Math.ceil(collection.length / size); x++) {
            var start = x * size;
            var end = start + size;
            result.push(collection.slice(start, end));
        }
        return result;
    };

    // export in node or browser
    if (typeof exports !== 'undefined') {
        if (typeof module !== 'undefined' && module.exports) {
            exports = module.exports = chunk;
        }
        exports.chunk = chunk;
    } else {
        this.chunk = chunk;
    }

}.call(window));

/**
*  Base64 encode / decode
*  http://www.webtoolkit.info/
**/
var Base64 = {
    // private property
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
    // public method for encoding
    encode : function (input) {
        var output = ""; var chr1, chr2, chr3, enc1, enc2, enc3, enc4; var i = 0;
        input = Base64._utf8_encode(input);
        while (i < input.length) {
            chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63;
            if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; }
            output = output + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
        }
        return output;
    },
    // public method for decoding
    decode : function (input) {
        var output = ""; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; var i = 0;
        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
        while (i < input.length) {
            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));
            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;
            output = output + String.fromCharCode(chr1);
            if (enc3 != 64) { output = output + String.fromCharCode(chr2); }
            if (enc4 != 64) { output = output + String.fromCharCode(chr3); }
        }
        output = Base64._utf8_decode(output);
        return output;
    },
    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";
        for (var n = 0; n < string.length; n++) {
            var c = string.charCodeAt(n);
            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }
        }
        return utftext;
    },
    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = ""; var i = 0; var c = c1 = c2 = 0;
        while ( i < utftext.length ) {
            c = utftext.charCodeAt(i);
            if (c < 128) { string += String.fromCharCode(c); i++; }
            else if((c > 191) && (c < 224)) { c2 = utftext.charCodeAt(i+1); string += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); i += 2; }
            else { c2 = utftext.charCodeAt(i+1); c3 = utftext.charCodeAt(i+2); string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); i += 3; }
        }
        return string;
    }
};

window.Carevault = {
    tokenExpiredBeforeSeconds: 60, //token租约续期检查间隔时间

    setItem: function (cname, cvalue, exmin) {
        if (window.sessionStorage) {
            window.sessionStorage.setItem(cname, cvalue);
        } else {
            var d = new Date();
            d.setTime(d.getTime() + (exmin * 60 * 1000));
            var expires = "expires=" + d.toGMTString();
            document.cookie = cname + "=" + cvalue + "; " + expires;
        }
    },

    getItem: function (cname) {
        if (window.sessionStorage){
           return window.sessionStorage.getItem(cname)
        }
        var name = cname + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i].trim();
            if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
        }
        return "";
    },

    setToken: function (cvalue) {
        this.setItem("token", cvalue);
//        if (cvalue) {
//            var str = Base64.decode(cvalue.split(".")[1]);
//            var keystr = "exp";
//            var expire_seconds = str.substring(str.indexOf(keystr) + keystr.length + 2, str.lastIndexOf(","));
//            //记录token过期时间，用于模拟会话保持
//            Carevault.setItem("token-expired", expire_seconds);
//        }
    },

    getToken: function () {
        return this.getItem("token");
    },

    refreshToken: function () {
        var self = this;
        Vue.http.get(Vue.http.options.root + '/tokenrefresh', { headers: { 'XAuthorization': 'Bearer ' + self.getToken() } })
        .then(function (res) {
            Carevault.setToken(res.data.token);
            console.log("vue token 续费成功！");
        })
        .catch(function (err) {
            console.log("残念！vue token 续费失败");
        });
    },

    tokenExpiredRemainSeconds: function () {
        // 计算token到期剩余时间
        // 单位时间为分钟
        return Math.ceil((this.getItem("token-expired") - Math.round(new Date().getTime() / 1000)) / 60);
    },

    getCookie: function (name) {
        var value = "; " + document.cookie;
        var parts = value.split("; " + name + "=");
        if (parts.length == 2) return parts.pop().split(";").shift();
    },

    setCookie: function (c_name, value, exdays) {
        var exdate = new Date();
        exdate.setDate(exdate.getDate() + exdays);
        var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
        document.cookie = c_name + "=" + c_value;
    }
};

// 统一设置正则表达式和字符串长度
window.reg = {
    inputReg: /^(?!_)(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5]+$/, // 中文、英文、数字、“_”

    getLength: function(str) {
        var realLength = 0, len = str.length, charCode = -1;
        for (var i = 0; i < len; i++) {
            charCode = str.charCodeAt(i);
            if (charCode >= 0 && charCode <= 128) realLength += 1;
            else realLength += 2;
        }
        return realLength;
    },
};

// 格式化日期
window.formatDate = function (date) {
    let y = date.getFullYear();
    let m = date.getMonth() + 1;
    m = m < 10 ? '0' + m : m;
    let d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    return y + '-' + m + '-' + d;
};

;(function () {

    // 开合用户中心和退出菜单
    $('#oscar-nav-btn').click(function () {
        $('.dada2').toggle();
    });

    // 开合左侧菜单
    $('#menu-toggle-btn').click(function () {
        var left = $('.left-sidebar'),
            main = $('.main-box'),
            $this = $(this);
        if (left.hasClass('damin')) {
            left.removeClass('damin').css('left', '0');
            main.css('padding-left', '240px');
            setTimeout(function () {
                $this.removeClass('menu-toggle-bg').css({"right": "0", "transform": "rotateY(0)"});
            }, 300);
        } else {
            left.addClass('damin').css('left', '-240px');
            main.css('padding-left', 0);
            setTimeout(function () {
                $this.addClass('menu-toggle-bg').css({"right": "-26px", "transform": "rotateY(180deg)"});
            }, 300);
        }
    });

    // 退出
    $('#login-out').click(function () {
        $('#login-out-form').submit();
    });

    // 定义树节点
    var treeMenuTemplate = [];
    treeMenuTemplate.push('<li class="el-submenu" :class="[open ? \'is-opened\': \'\', selected ? \'is-active\':\'\']">');
    treeMenuTemplate.push('<a class="db el-submenu__title" :id="model.index" @click="toggle" v-menu-animation="open" :style="{paddingLeft: paddingLeft + \'px\'}" :href="getUrl">');
    treeMenuTemplate.push('<i :class="model.icon" v-if="level == 1" style="color:#c7c7c7;"></i>');
    treeMenuTemplate.push('<template v-if="hasChildren()">');
    treeMenuTemplate.push('<i class="el-submenu__icon-arrow" :class="\'el-icon-arrow-down\'"></i>');
    treeMenuTemplate.push('</template>');
    treeMenuTemplate.push('{{ model.menuName }}');
    treeMenuTemplate.push('</a>');
    treeMenuTemplate.push('<ul class="el-menu" :class="[open ? \'\' : \'dn\']" v-if="hasChildren()">');
    treeMenuTemplate.push('<tree-menu v-for="item in model.children" :model="item" :level="level + 1" :theId="theId"></tree-menu>');
    treeMenuTemplate.push('</ul>');
    treeMenuTemplate.push('</li>');

    var treeMenu = Vue.component('tree-menu', {
        template: treeMenuTemplate.join(''),

        created: function () {
            var index = this.model.index;
            var hasIndex = this.theId.search(index);
            var lala = index.replace(this.theId, '');
            if (hasIndex == 0) {
                this.open = true;
            }
            if (hasIndex == 0 && lala.length == 0) {
                this.selected = true;
            }
        },

        props: ['model', 'level', 'theId'],

        computed: {
            getUrl: function () {
                if (this.hasChildren()) {
                    return "javascript:;";
                }
                return this.$http.options.root + '' + this.model.url;
            }
        },

        data: function () {
            return {
                open: false,
                paddingLeft: this.level * 20 + (this.level == 1 ? 0 : this.level) * 4,
                selected: false
            };
        },

        methods: {
            hasChildren: function () {
                return this.model.children && this.model.children.length;
            },

            toggle: function () {
                if (this.hasChildren()) {
                    this.open = !this.open;
                }
            }
        }

    });

    Vue.directive('menu-animation', function (el, binding) {
        var open = (binding.value);
        var ulElement = $(el).parent().children('ul');
        if (open) {
            ulElement.slideDown(200);
        } else {
            ulElement.slideUp(200);
        }
    });

    // 定义外围树
    var bigTreeTemplate = [];
    bigTreeTemplate.push('<div class="tree-menu" v-bind:value="value" v-on:input="$emit(\'input\', $event.target.value)">');
    bigTreeTemplate.push('<ul v-for="menuItem in theModel" class="el-menu">');
    bigTreeTemplate.push('<tree-menu :model="menuItem" :level="theLevel" :theId="defaultActive"></tree-menu>');
    bigTreeTemplate.push('</ul>');
    bigTreeTemplate.push('</div>');

    Vue.component('big-tree', {
        template: bigTreeTemplate.join(''),

        props: ['defaultActive', 'value'],

        created: function () {
            // 设置初始选中项
            var value = $('#defaultActive').val();
            this.defaultActive = value;

            // 设置菜单项
            var haha = setInterval( () => {
                if (this.value.length > 0) clearInterval(haha);
                this.theModel = this.value;
            }, 10);
        },

        data: function () {
            return {
                theModel: null,
                theLevel: 1
            };
        },

        components: {
            'tree-menu': treeMenu
        }
    });

    // 搜索条件
    Vue.component('search-condition', {
        name: 'search-condition',

        template: `
            <div id="searchBox" v-on:input="$emit('input', $event.target.value)">
                <dl class="my-condition sfilter-tag fix indexChoose" v-if="items.length > 0">
                    <div class="l mt5" style="width:76px;">
                        <dt>已选条件</dt>
                    </div>
                    <div class="l" style="width:80%;">
                        <template v-for="item in items">
                            <el-tag closable type="info"
                                class="mr10 mb10"
                                :disable-transitions="false"
                                @close="removeItem(item)">
                                {{ item.label }}
                            </el-tag>
                        </template>
                    </div>
                </dl>

                <dl class="sfilter-tag fix indexChoose" id="indexOld" v-for="(item, index) in itemList">
                    <div class="l" style="width:76px;">
                        <dt>{{item.title}}</dt>
                    </div>
                    <div class="l" style="width:80%;" >
                        <dd v-for="(value, index2) in item.value" @click="addItem(item.key, value)">
                            <template v-if="index2 < 5">
                                <a href="javascript:;">{{ value.label }}</a>
                            </template>
                            <template v-else>
                                <a href="javascript:;" v-show="item.showFlag">{{ value.label }}</a>
                            </template>
                        </dd>
                    </div>

                    <a class="btn btn-link btn-sm pull-right v3_a_more" style="margin-top:-4px;" v-if="item.value.length > 5" @click="showItem(index)">
                        <span v-if="!item.showFlag">更多</span>
                        <span v-if="item.showFlag">收起</span>
                        <i class="el-icon-arrow-down" v-if="!item.showFlag"></i>
                        <i class="el-icon-arrow-up" v-if="item.showFlag"></i>
                    </a>
                </dl>

                <slot></slot>
            </div>`,

        data () {
            return {
                items: [],
            };
        },

        props: ['itemList', 'value'],

        created () {
        },

        methods: {
            showItem (index) {
                this.itemList = this.itemList.map((node, index2) => {
                    if (index == index2) {
                        node.showFlag = !node.showFlag;
                    }
                    return node;
                });
            },

            addItem (key, item) {
                for (let i = 0; i < this.items.length; i++) {
                    if (this.items[i].value + '-' + this.items[i].label == item.value + '-' + item.label) return;
                }
                item.key = key;
                this.items.push(item);
                this.$emit('condition-change', item, this.items);
            },

            removeItem (item) {
                let index = 0;
                for (let i = 0; i < this.items.length; i++) {
                    let temp = this.items[i];
                    if (temp.value + '-' + temp.label == item.value + '-' + item.label) {
                        index = i;
                        break;
                    }
                }
                this.items.splice(index, 1);
                this.$emit('condition-change', item, this.items);
            },
        },

        mounted () {
            this.itemList = this.itemList.map((node) => {
                node.showFlag = false;
                return node;
            });
            this.items = this.value;
        },

    });

}) ()
